package access

import (
	"encoding/json"
	"errors"
	"server/common"

	"github.com/gorilla/websocket"
)

// -------------------------------------------------------------------------------------------------
//
// -------------------------------------------------------------------------------------------------
func (s *AccessService) sendMsgToConnection(msg common.Message, connId string) error {
	conn, ok := s.connMgr.GetConn(connId)
	if !ok {
		return errors.New("connection not found")
	}

	data, err := json.Marshal(msg)
	if err != nil {
		common.Logger(common.SERVICE_TYPE_ACCESS).Errorf("failed to marshal message: %v", err)
		return err
	}

	common.Logger(common.SERVICE_TYPE_ACCESS).WithField("msg", common.ToJson(msg)).
		Info("Sending message to connection:", connId)

	if err := conn.WriteMessage(websocket.TextMessage, data); err != nil {
		common.Logger(common.SERVICE_TYPE_ACCESS).
			Errorf("failed to write message to WebSocket: %v", err)
	}

	return nil
}
